package admin

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"reflect"
	"strconv"
	"time"
	"zhuandan/data_source"
	"zhuandan/models"
	"zhuandan/utils"
)

var (
	defaultSheetName = "Sheet1" //默认Sheet名称
	defaultHeight    = 25.0     //默认行高度
)

type lzExcelExport struct {
	file      *excelize.File
	sheetName string //可定义默认sheet名称
}

func NewMyExcel() *lzExcelExport {
	return &lzExcelExport{file: createFile(), sheetName: defaultSheetName}
}

// 导出基本的表格
func (l *lzExcelExport) ExportToPath(params []map[string]string, data []map[string]interface{}, path string) (string, error) {
	l.export(params, data)
	name := createFileName()
	filePath := path + "/" + name
	err := l.file.SaveAs(filePath)
	return filePath, err
}

// 导出到浏览器。此处使用的gin框架 其他框架可自行修改ctx
func (l *lzExcelExport) ExportToWeb(params []map[string]string, data []map[string]interface{}, c *gin.Context) {
	l.export(params, data)
	buffer, _ := l.file.WriteToBuffer()
	//设置文件类型
	c.Header("Content-Type", "application/vnd.ms-excel;charset=utf8")
	//设置文件名称
	c.Header("Content-Disposition", "attachment; filename="+url.QueryEscape(createFileName()))
	_, _ = c.Writer.Write(buffer.Bytes())
}

// 设置首行
func (l *lzExcelExport) writeTop(params []map[string]string) {
	topStyle, _ := l.file.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{
			Horizontal: "center",
		},
		Font: &excelize.Font{
			Family: "宋体",
			Size:   10,
		},
	})
	var word = 'A'
	//首行写入
	for _, conf := range params {
		title := conf["title"]
		width, _ := strconv.ParseFloat(conf["width"], 64)
		line := fmt.Sprintf("%c1", word)
		//设置标题
		_ = l.file.SetCellValue(l.sheetName, line, title)
		//列宽
		_ = l.file.SetColWidth(l.sheetName, fmt.Sprintf("%c", word), fmt.Sprintf("%c", word), width)
		//设置样式
		_ = l.file.SetCellStyle(l.sheetName, line, line, topStyle)
		word++
	}
}

// 写入数据
func (l *lzExcelExport) writeData(params []map[string]string, data []map[string]interface{}) {
	lineStyle, _ := l.file.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{
			Horizontal: "center",
		},
		Font: &excelize.Font{
			Family: "宋体",
			Size:   10,
		},
	})
	//数据写入
	var j = 2 //数据开始行数
	for i, val := range data {
		//设置行高
		_ = l.file.SetRowHeight(l.sheetName, i+1, defaultHeight)
		//逐列写入
		var word = 'A'
		for _, conf := range params {
			valKey := conf["key"]
			line := fmt.Sprintf("%c%v", word, j)
			isNum := conf["is_num"]

			//设置值
			if isNum != "0" {
				valNum := fmt.Sprintf("'%v", val[valKey])
				_ = l.file.SetCellValue(l.sheetName, line, valNum)
			} else {
				_ = l.file.SetCellValue(l.sheetName, line, val[valKey])
			}

			//设置样式
			_ = l.file.SetCellStyle(l.sheetName, line, line, lineStyle)
			word++
		}
		j++
	}
	//设置行高 尾行
	_ = l.file.SetRowHeight(l.sheetName, len(data)+1, defaultHeight)
}

func (l *lzExcelExport) export(params []map[string]string, data []map[string]interface{}) {
	l.writeTop(params)
	l.writeData(params, data)
}

func createFile() *excelize.File {
	f := excelize.NewFile()
	// 创建一个默认工作表
	sheetName := defaultSheetName
	index, _ := f.NewSheet(sheetName)
	// 设置工作簿的默认工作表
	f.SetActiveSheet(index)
	return f
}

func createFileName() string {
	name := time.Now().Format("2006-01-02-15-04-05")
	rand.Seed(time.Now().UnixNano())
	return fmt.Sprintf("excle-%v-%v.xlsx", name, rand.Int63n(time.Now().Unix()))
}

// excel导出(数据源为Struct) []interface{}
func (l *lzExcelExport) ExportExcelByStruct(titleList []string, data []interface{}, fileName string, sheetName string, c *gin.Context) error {
	l.file.SetSheetName("Sheet1", sheetName)
	header := make([]string, 0)
	for _, v := range titleList {
		header = append(header, v)
	}
	rowStyleID, _ := l.file.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{
			Horizontal: "center",
		},
		Font: &excelize.Font{
			Family: "宋体",
			Size:   10,
		},
	})
	_ = l.file.SetSheetRow(sheetName, "A1", &header)
	_ = l.file.SetRowHeight("Sheet1", 1, 30)
	length := len(titleList)
	headStyle := Letter(length)

	//return
	var lastRow string
	var widthRow string
	for k, v := range headStyle {

		if k == length-1 {

			lastRow = fmt.Sprintf("%s1", v)
			widthRow = v
		}
	}
	if err := l.file.SetColWidth(sheetName, "A", widthRow, 30); err != nil {
		fmt.Print("错误--", err.Error())
	}
	rowNum := 1
	for _, v := range data {

		t := reflect.TypeOf(v)
		fmt.Print("--ttt--", t.NumField())
		value := reflect.ValueOf(v)
		row := make([]interface {
		}, 0)
		for l := 0; l < t.NumField(); l++ {

			val := value.Field(l).Interface()
			row = append(row, val)
		}
		rowNum++
		err := l.file.SetSheetRow(sheetName, "A"+strconv.Itoa(rowNum), &row)
		_ = l.file.SetCellStyle(sheetName, fmt.Sprintf("A%d", rowNum), fmt.Sprintf("%s", lastRow), rowStyleID)
		if err != nil {
			return err
		}
	}
	disposition := fmt.Sprintf("attachment; filename=%s.xlsx", url.QueryEscape(fileName))
	c.Writer.Header().Set("Content-Type", "application/octet-stream")
	c.Writer.Header().Set("Content-Disposition", disposition)
	c.Writer.Header().Set("Content-Transfer-Encoding", "binary")
	c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
	return l.file.Write(c.Writer)
}

// Letter 遍历a-z
func Letter(length int) []string {
	var str []string
	for i := 0; i < length; i++ {
		str = append(str, string(rune('A'+i)))
	}
	return str
}

func rands(min, max float32) float64 {
	max = max - min
	rand.Seed(time.Now().UnixNano()) //设置随机种子，使每次结果不一样
	res := Round2(float64(min+max*rand.Float32()), 2)
	return res
}
func Round2(f float64, n int) float64 {
	floatStr := fmt.Sprintf("%."+strconv.Itoa(n)+"f", f)
	inst, _ := strconv.ParseFloat(floatStr, 64)
	return inst
}

type Procureordershtk struct {
	ID        int64   `gorm:"column:id" json:"id"`
	Title     string  `gorm:"column:title" json:"title"`
	Fbrphone  string  `gorm:"column:fbrphone" json:"fbrphone"`
	Phone     string  `gorm:"column:phone" json:"phone"`
	Nickname  string  `gorm:"column:nickname" json:"nickname"` //  昵称
	Price     float64 `gorm:"column:price" json:"price"`
	Num       int64   `gorm:"column:num" json:"num"`
	Allprice  float64 `gorm:"column:allprice" json:"allprice"`
	Status    string  `gorm:"column:status" json:"status"`
	Addtime   string  `gorm:"column:addtime" json:"addtime"`
	Tktime    string  `gorm:"column:tktime" json:"tktime"`
	Userprice float64 `gorm:"column:userprice" json:"userprice"`
}

func Excelshtk(ctx *gin.Context) {
	phone := ctx.Query("phone")
	status := ctx.Query("status")
	nickname := ctx.Query("nickname")
	endtime := ctx.Query("endtime")
	paytime := ctx.Query("paytime")

	var users []models.Procureordersql
	res := data_source.Db.Model(&models.Procureorder{}).Select("procureorder.*, procure.province, procure.city, procure.content, procure.name, procure.phone as khphone, procure.addtime as fbaddtime, procure.fbrphone, user.nickname").Joins("left join procure on procure.id = procureorder.procureid").Joins("left join user on user.id = procureorder.uid")
	if phone != "" {
		res = res.Where("procureorder.phone = ?", phone)
	}
	if nickname != "" {
		res = res.Where("user.nickname = ?", nickname)
	}
	if status != "0" {
		res = res.Where("procureorder.status = ?", status)
	} else {
		res = res.Where("procureorder.status > 2")
	}

	if paytime != "" {
		res = res.Where("procureorder.tktime >= ?", paytime)
	}
	if endtime != "" {
		res = res.Where("procureorder.tktime < ?", utils.StrToInt64(endtime)+86400)
	}

	res.Order("procureorder.updatetime desc").Find(&users)

	titles := []string{"ID", "转单信息", "发布人手机号", "购买会员手机号", "购买会员昵称", "单个金额", "购买数量", "总金额", "状态", "购买时间", "退款时间"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range users {
		addtime := time.Unix(t.Addtime, 0).Format("2006-01-02 15:04:05")
		tktime := time.Unix(t.Tktime, 0).Format("2006-01-02 15:04:05")

		status := "已付款"
		if t.Status == 2 {
			status = "已到账"
		} else if t.Status == 3 {
			status = "申请退款"
		} else if t.Status == 3 {
			status = "申请退款"
		} else if t.Status == 3 {
			status = "申请退款"
		}
		datas = append(datas, Procureordershtk{
			ID:       t.ID,
			Title:    t.Title,
			Fbrphone: t.Fbrphone,
			Phone:    t.Phone,
			Nickname: t.Nickname,
			Price:    t.Price,
			Num:      t.Num,
			Allprice: t.Price * float64(t.Num),
			Status:   status,
			Addtime:  addtime,
			Tktime:   tktime,
		})
	}
	ex.ExportExcelByStruct(titles, datas, "售后退款导出", "用户", ctx)

}

func Excelbuy(ctx *gin.Context) {
	phone := ctx.Query("phone")
	status := ctx.Query("status")
	nickname := ctx.Query("nickname")
	paytime := ctx.Query("paytime")
	endtime := ctx.Query("endtime")

	var users []models.Procureordersql
	res := data_source.Db.Debug().Model(&models.Procureorder{}).Select("procureorder.*, procure.province, procure.city, procure.content, procure.name, procure.phone as khphone, procure.addtime as fbaddtime, user.nickname, procure.fbrphone, procure.price, user.price as userprice").Joins("left join procure on procure.id = procureorder.procureid").Joins("left join user on user.id = procureorder.uid")
	if phone != "" {
		res = res.Where("procureorder.phone = ?", phone)
	}
	if nickname != "" {
		res = res.Where("user.nickname = ?", nickname)
	}
	if status != "0" && status != "" {
		res = res.Where("procureorder.status = ?", status)
	}
	if paytime != "" {
		res = res.Where("procureorder.addtime >= ?", paytime)
	}
	if endtime != "" {
		res = res.Where("procureorder.addtime < ?", utils.StrToInt64(endtime)+86400)
	}
	res.Order("procureorder.updatetime desc").Find(&users)

	//fmt.Println(users)
	//return

	titles := []string{"ID", "转单信息", "发布人手机号", "购买会员手机号", "购买会员昵称", "单个金额", "购买数量", "总金额", "状态", "购买时间", "退款时间", "用户余额"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range users {
		addtime := time.Unix(t.Addtime, 0).Format("2006-01-02 15:04:05")
		tktime := time.Unix(t.Tktime, 0).Format("2006-01-02 15:04:05")

		statuszt := "已付款"
		if t.Status == 2 {
			statuszt = "已到账"
		} else if t.Status == 3 {
			statuszt = "申请退款"
		} else if t.Status == 3 {
			statuszt = "申请退款"
		} else if t.Status == 3 {
			statuszt = "申请退款"
		}
		datas = append(datas, Procureordershtk{
			ID:        t.ID,
			Title:     t.Title,
			Fbrphone:  t.Fbrphone,
			Phone:     t.Phone,
			Nickname:  t.Nickname,
			Price:     t.Price,
			Num:       t.Num,
			Allprice:  t.Price * float64(t.Num),
			Status:    statuszt,
			Addtime:   addtime,
			Tktime:    tktime,
			Userprice: t.Userprice,
		})
	}
	ex.ExportExcelByStruct(titles, datas, "售后退款导出", "用户", ctx)

}

type ExcelprocuresRBody struct {
	ID            int64   `gorm:"column:id" json:"id"`
	Classifytitle string  `gorm:"column:classifytitle" json:"classifytitle"`
	Title         string  `gorm:"column:title" json:"title"`
	Userphone     string  `gorm:"column:userphone" json:"userphone"`
	Nickname      string  `gorm:"column:nickname" json:"nickname"`
	Name          string  `gorm:"column:name" json:"name"`
	Phone         string  `gorm:"column:phone" json:"phone"`
	Buynum        int64   `gorm:"column:buynum" json:"buynum"`
	Addtime       string  `gorm:"column:addtime" json:"addtime"`
	Province      string  `gorm:"column:province" json:"province"`
	City          string  `gorm:"column:city" json:"city"`
	County        string  `gorm:"column:county" json:"county"`
	Fasong        string  `gorm:"column:fasong" json:"fasong"`
	Price         float64 `gorm:"column:price" json:"price"`
	Num           int64   `gorm:"column:num" json:"num"`
	Jingli        string  `gorm:"column:jingli" json:"jingli"`
	Jingliname    string  `gorm:"column:jingliname" json:"jingliname"`
	Laiyuanval    string  `gorm:"column:laiyuanval" json:"laiyuanval"`
	Content       string  `gorm:"column:content" json:"content"` //  描述
}

func Excelprocures(ctx *gin.Context) {
	phone := ctx.Query("phone")
	userphone := ctx.Query("userphone")
	name := ctx.Query("name")
	classifyid := ctx.Query("classifyid")
	fasong := ctx.Query("fasong")
	paytime := ctx.Query("paytime")
	endtime := ctx.Query("endtime")
	laiyuanval := ctx.Query("laiyuanval")
	adminid := ctx.Query("adminid")
	//fmt.Println(paytime)
	//fmt.Println(endtime)
	if adminid == "" || adminid == "0" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    "请登录",
			"msg":     "ok",
		})
		return
	} else {
		adminlog := models.Adminlog{
			Adminid: utils.StrToInt64(adminid),
			Addtime: time.Now().Unix(),
			Content: "导出转单记录:",
		}
		data_source.Db.Create(&adminlog)
	}

	if paytime == "" || endtime == "" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    "请选择时间进行导出",
			"msg":     "ok",
		})
		return
	}
	var users []models.Procuresql
	res := data_source.Db.Debug().Model(&models.Procure{}).Select("procure.*, user.nickname, user.phone as userphone, user.jingli, user.jingliname").Joins("left join user on user.id = procure.uid").Where("procure.state = 1")
	if classifyid != "" {
		res = res.Where("procure.classifyid = ?", classifyid)
	}
	if paytime != "" {
		res = res.Where("procure.addtime >= ?", paytime)
	}
	if endtime != "" {
		res = res.Where("procure.addtime < ?", endtime)
	}
	if fasong != "0" && fasong != "" {
		res = res.Where("procure.fasong = ?", fasong)
	}
	if name != "" {
		res = res.Where("procure.title like ? or user.nickname like ?", "%"+name+"%", "%"+name+"%")
	}
	if phone != "" {
		res = res.Where("procure.phone = ?", phone)
	}
	if userphone != "" {
		res = res.Where("user.phone = ?", userphone)
	}
	if laiyuanval != "" {
		res = res.Where("procure.laiyuanval like ?", "%"+laiyuanval+"%")
	}
	res.Order("user.id desc").Find(&users)

	titles := []string{"ID", "分类", "标题", "发布人手机号", "发布人", "联系人", "联系电话", "已售", "发布时间", "省", "城市", "区县", "是否推送", "单价", "购买数量", "项目经理手机号", "项目经理", "来源", "详细内容"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range users {
		addtime := time.Unix(t.Addtime, 0).Format("2006-01-02 15:04:05")

		tuisong := "未推送"
		if t.Fasong == 2 {
			tuisong = "推送一次"
		}
		if t.Fasong == 3 {
			tuisong = "推送两次"
		}
		var phoneval string
		if adminid == "36" || adminid == "33" {
			phoneval = t.Phone
		} else {
			phoneval = MaskPhone(t.Phone)
		}

		datas = append(datas, ExcelprocuresRBody{
			ID:            t.ID,
			Classifytitle: t.Classifytitle,
			Title:         t.Title,
			Userphone:     t.Userphone,
			Nickname:      t.Nickname,
			Name:          t.Name,
			Phone:         phoneval,
			Buynum:        t.Buynum,
			Addtime:       addtime,
			Province:      t.Province,
			City:          t.City,
			County:        t.County,
			Fasong:        tuisong,
			Price:         t.Price,
			Num:           t.Num,
			Jingli:        t.Jingli,
			Jingliname:    t.Jingliname,
			Laiyuanval:    t.Laiyuanval,
			Content:       t.Content,
		})
	}

	ex.ExportExcelByStruct(titles, datas, "转单记录导出", "用户", ctx)

}
func MaskPhone(phone string) string {
	if len(phone) <= 10 {
		return phone
	}
	return phone[:3] + "****" + phone[6:]
}

type ExcelprocurelogsRBody struct {
	ID       int64  `json:"id" gorm:"id"`
	Title    string `gorm:"column:title" json:"title"`
	Nickname string `gorm:"column:nickname" json:"nickname"` //  昵称
	Phone    string `gorm:"column:phone" json:"phone"`       //  手机号
	Addtime  string `json:"addtime" gorm:"addtime"`
}

func Excelprocurelogs(ctx *gin.Context) {
	procuresid := ctx.Query("procuresid")
	paytime := ctx.Query("paytime")
	endtime := ctx.Query("endtime")

	var procurelog []models.Procurelogsql
	res := data_source.Db.Model(&models.Procurelog{}).Select("procurelog.*, user.nickname, user.phone").Joins("left join user on user.id = procurelog.uid").Where("procurelog.procureid = ?", procuresid)
	//res := data_source.Db
	if paytime != "" && paytime != "0" {
		res = res.Where("procurelog.addtime >= ?", paytime)
	}
	if endtime != "" && endtime != "0" {
		res = res.Where("procurelog.addtime < ?", utils.StrToInt64(endtime)+86400)
	}
	res.Order("procurelog.id desc").Find(&procurelog)
	//fmt.Println(procurelog)
	titles := []string{"ID", "标题", "访问人", "访问人手机号", "访问时间"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range procurelog {
		addtime := time.Unix(t.Addtime, 0).Format("2006-01-02 15:04:05")

		datas = append(datas, ExcelprocurelogsRBody{
			ID:       t.ID,
			Title:    t.Title,
			Nickname: t.Nickname,
			Phone:    t.Phone,
			Addtime:  addtime,
		})
	}

	ex.ExportExcelByStruct(titles, datas, "转单访问记录导出", "用户", ctx)

}

type ExceltixianRBody struct {
	ID        int64   `gorm:"column:id" json:"id"`
	Nickname  string  `gorm:"column:nickname" json:"nickname"`
	Phone     string  `gorm:"column:phone" json:"phone"`
	Title     string  `gorm:"column:title" json:"title"`
	Yuanprice float64 `gorm:"column:yuanprice" json:"yuanprice"`
	Price     float64 `gorm:"column:price" json:"price"`
	Sxf       float64 `gorm:"column:sxf" json:"sxf"`
	Dzprice   float64 `gorm:"column:dzprice" json:"dzprice"`
	Addtime   string  `gorm:"column:addtime" json:"addtime"`
	Yinghang  string  `gorm:"column:yinghang" json:"yinghang"`
}

func Exceltixian(ctx *gin.Context) {
	paytime := ctx.Query("paytime")
	endtime := ctx.Query("endtime")
	state := ctx.Query("state")

	var users1 []models.Usertixiansql
	res := data_source.Db.Model(&models.Usertixian{}).Select("usertixian.*, user.phone, user.nickname").Joins("left join user on user.id = usertixian.uid")
	if state != "0" {
		res = res.Where("usertixian.state = ?", state)
	}
	if paytime != "" {
		res = res.Where("usertixian.addtime >= ?", paytime)
	}
	if endtime != "" {
		res = res.Where("usertixian.addtime < ?", utils.StrToInt64(endtime)+86400)
	}
	res.Order("usertixian.id desc").Find(&users1)

	var bankidarr []int64
	for _, v := range users1 {
		if v.Bankid > 0 {
			bankidarr = append(bankidarr, v.Bankid)
		}
	}
	if len(bankidarr) > 0 {
		var banks []models.Bank
		data_source.Db.Where("id in (?)", bankidarr).Find(&banks)

		for k, v := range users1 {
			for _, b := range banks {
				if v.Bankid == b.ID {
					users1[k].Bank = b
				}
			}
		}

	}

	titles := []string{"ID", "用户名称", "手机号", "备注", "提现前余额", "提现金额", "手续费", "实际到账", "时间", "银行卡信息"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range users1 {
		addtime := time.Unix(t.Addtime, 0).Format("2006-01-02 15:04:05")
		yhkxx := t.Bank.Name + "," + t.Bank.Phone + "," + t.Bank.Kaihuhang + "," + t.Bank.Bank
		datas = append(datas, ExceltixianRBody{
			ID:        t.ID,
			Nickname:  t.Nickname,
			Phone:     t.Phone,
			Title:     t.Title,
			Yuanprice: t.Yuanprice,
			Price:     t.Price,
			Sxf:       t.Sxf,
			Dzprice:   t.Dzprice,
			Addtime:   addtime,
			Yinghang:  yhkxx,
		})
	}

	ex.ExportExcelByStruct(titles, datas, "提现记录导出", "用户", ctx)

}

type ExcelProcurelogRBody struct {
	ID        int64   `json:"id" gorm:"id"`
	Addtime   string  `json:"addtime" gorm:"addtime"`
	Procureid int64   `json:"procureid" gorm:"procureid"`
	Title     string  `gorm:"column:title" json:"title"`
	Userprice float64 `gorm:"column:userprice" json:"userprice"`
	Phone     string  `gorm:"column:phone" json:"phone"`       //  手机号
	Nickname  string  `gorm:"column:nickname" json:"nickname"` //  昵称
}

func ExcelProcurelog(ctx *gin.Context) {
	inttime := ctx.Query("inttime")
	endtime := ctx.Query("endtime")
	phone := ctx.Query("phone")
	nickname := ctx.Query("nickname")
	title := ctx.Query("title")

	var users1 []models.Procurelogsql
	res := data_source.Db.Model(&models.Procurelog{}).Select("procurelog.*, user.nickname,  user.logo, user.phone").Joins("left join user on user.id = procurelog.uid")
	//res := data_source.Db
	if inttime != "" {
		res = res.Where("procurelog.addtime >= ?", inttime)
	}
	if endtime != "" {
		res = res.Where("procurelog.addtime < ?", utils.StrToInt64(endtime)+86400)
	}
	if nickname != "" {
		res = res.Where("user.nickname = ?", nickname)
	}
	if phone != "" {
		res = res.Where("user.phone = ?", phone)
	}
	if title != "" {
		res = res.Where("procurelog.title = ?", title)
	}
	res.Order("procurelog.id desc").Find(&users1)

	titles := []string{"ID", "时间", "转单id", "转单名称", "用户余额", "手机号", "昵称"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range users1 {
		addtime := time.Unix(t.Addtime, 0).Format("2006-01-02 15:04:05")

		datas = append(datas, ExcelProcurelogRBody{
			ID:        t.ID,
			Addtime:   addtime,
			Procureid: t.Procureid,
			Title:     t.Title,
			Userprice: t.Userprice,
			Phone:     t.Phone,
			Nickname:  t.Nickname,
		})
	}

	ex.ExportExcelByStruct(titles, datas, "浏览记录导出", "浏览记录", ctx)

}

type ExceluserRBody struct {
	ID       int64   `json:"id" gorm:"id"`
	Addtime  string  `json:"addtime" gorm:"addtime"`
	Phone    string  `gorm:"column:phone" json:"phone"`       //  手机号
	Nickname string  `gorm:"column:nickname" json:"nickname"` //  昵称
	Price    float64 `gorm:"column:price" json:"price"`       //余额
	Fbnum    int64   `gorm:"column:fbnum" json:"fbnum"`
}

func Exceluser(ctx *gin.Context) {

	var users1 []models.User
	res := data_source.Db
	res.Order("id desc").Find(&users1)

	titles := []string{"ID", "浏览时间", "手机号", "名称", "用户余额", "发布次数"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range users1 {
		addtime := time.Unix(t.CreateTime, 0).Format("2006-01-02 15:04:05")

		datas = append(datas, ExceluserRBody{
			ID:       t.ID,
			Addtime:  addtime,
			Phone:    t.Phone,
			Nickname: t.Nickname,
			Price:    t.Price,
			Fbnum:    t.Fbnum,
		})
	}

	ex.ExportExcelByStruct(titles, datas, "浏览记录导出", "浏览记录", ctx)

}

type ExcelfabulogRBody struct {
	ID       int64  `json:"id" gorm:"id"`
	Addtime  string `json:"addtime" gorm:"addtime"`
	Phone    string `gorm:"column:phone" json:"phone"`       //  手机号
	Nickname string `gorm:"column:nickname" json:"nickname"` //  昵称
}

func Excelfabulog(ctx *gin.Context) {
	inttime := ctx.Query("inttime")
	endtime := ctx.Query("endtime")
	nickname := ctx.Query("nickname")
	phone := ctx.Query("phone")
	var users []models.Fabulogsql
	res := data_source.Db.Model(&models.Fabulog{}).Select("fabulog.*, user.nickname,  user.logo, user.phone").Joins("left join user on user.id = fabulog.uid")
	//res := data_source.Db
	if inttime != "" {
		res = res.Where("fabulog.addtime >= ?", inttime)
	}
	if endtime != "" {
		res = res.Where("fabulog.addtime < ?", utils.StrToInt64(endtime)+86400)
	}
	if nickname != "" {
		res = res.Where("user.nickname = ?", nickname)
	}
	if phone != "" {
		res = res.Where("user.phone = ?", phone)
	}

	res.Order("fabulog.id desc").Find(&users)

	titles := []string{"ID", "打开时间", "手机号", "名称"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range users {
		addtime := time.Unix(t.Addtime, 0).Format("2006-01-02 15:04:05")

		datas = append(datas, ExcelfabulogRBody{
			ID:       t.ID,
			Addtime:  addtime,
			Phone:    t.Phone,
			Nickname: t.Nickname,
		})
	}

	ex.ExportExcelByStruct(titles, datas, "打开记录导出", "打开记录导出", ctx)

}

type ExcelchongzhiRBody struct {
	ID       int64   `json:"id" gorm:"id"`
	Nickname string  `gorm:"column:nickname" json:"nickname"` //  昵称
	Phone    string  `gorm:"column:phone" json:"phone"`       //  手机号
	Price    float64 `gorm:"column:price" json:"price"`       //  金额
	Title    string  `gorm:"column:title" json:"title"`       //  备注
	Addtime  string  `json:"addtime" gorm:"addtime"`
}

func Excelchongzhi(ctx *gin.Context) {
	inttime := ctx.Query("paytime")
	endtime := ctx.Query("endtime")
	phone := ctx.Query("phone")
	var users []models.Buyordersql
	res := data_source.Db.Model(&models.Buyorder{}).Select("buyorder.*, user.phone, user.nickname").Joins("left join user on user.id = buyorder.uid").Where("buyorder.status = 2").Where("buyorder.price > 0")
	//res := data_source.Db
	if inttime != "" {
		res = res.Where("buyorder.addtime >= ?", inttime)
	}
	if endtime != "" {
		res = res.Where("buyorder.addtime < ?", utils.StrToInt64(endtime)+86400)
	}
	if phone != "" {
		res = res.Where("user.phone = ?", phone)
	}
	res.Order("buyorder.id desc").Find(&users)

	titles := []string{"ID", "昵称", "手机号", "金额", "备注", "时间"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range users {
		addtime := time.Unix(t.Addtime, 0).Format("2006-01-02 15:04:05")

		datas = append(datas, ExcelchongzhiRBody{
			ID:       t.ID,
			Nickname: t.Nickname,
			Phone:    t.Phone,
			Price:    t.Price,
			Title:    t.Title,
			Addtime:  addtime,
		})
	}

	ex.ExportExcelByStruct(titles, datas, "充值记录导出", "充值记录导出", ctx)

}

type ExceluserfdRBody struct {
	ID       int64  `json:"id" gorm:"id"`
	Nickname string `gorm:"column:nickname" json:"nickname"` //  昵称
	Phone    string `gorm:"column:phone" json:"phone"`       //  手机号
	Addtime  string `json:"addtime" gorm:"addtime"`
}

func Exceluserfd(ctx *gin.Context) {
	var users []models.User
	data_source.Db.Where("fbnum > 0").Find(&users)

	titles := []string{"ID", "昵称", "手机号", "上次发单时间"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range users {
		addtime := time.Unix(t.Fbtime, 0).Format("2006-01-02 15:04:05")

		datas = append(datas, ExceluserfdRBody{
			ID:       t.ID,
			Nickname: t.Nickname,
			Phone:    t.Phone,
			Addtime:  addtime,
		})
	}

	ex.ExportExcelByStruct(titles, datas, "记录导出", "记录导出", ctx)

}

//
//func Exceluserfd(ctx *gin.Context) {
//
//	var tuisong []models.Tuisongshezhi
//	data_source.Db.Where("state = 1").Where("classifyid = 66").Find(&tuisong)
//	var uids []int64
//	for _, t := range tuisong {
//		uids = append(uids, t.Uid)
//	}
//	var users []models.User
//	data_source.Db.Where("id in (?)", uids).Find(&users)
//
//	titles := []string{"ID", "昵称", "手机号", "上次发单时间"}
//
//	ex := NewMyExcel()
//
//	var datas []interface{}
//	for _, t := range users {
//		addtime := time.Unix(t.Fbtime, 0).Format("2006-01-02 15:04:05")
//
//		datas = append(datas, ExceluserfdRBody{
//			ID:       t.ID,
//			Nickname: t.Nickname,
//			Phone:    t.Phone,
//			Addtime:  addtime,
//		})
//	}
//
//	ex.ExportExcelByStruct(titles, datas, "记录导出", "记录导出", ctx)
//
//}

func Gongchengdaoru(ctx *gin.Context) {
	files, _ := ctx.FormFile("file")
	unix_int := time.Now().Unix()                    // 时间戳，int类型
	time_unix_str := strconv.FormatInt(unix_int, 10) // 讲int类型转为string类型，方便拼接，使用sprinf也可以

	file_path := "upload/excel/" + time_unix_str + files.Filename
	ctx.SaveUploadedFile(files, file_path)
	xlsx, err := excelize.OpenFile(file_path)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// 获取excel中具体的列的值
	sheets := xlsx.GetSheetList()

	rows, _ := xlsx.GetRows(sheets[0])

	if len(rows) == 0 {
		rows1, _ := xlsx.GetRows(sheets[0])
		rows = rows1
	}
	var num int64
	for key, row := range rows {
		if key == 0 {
			continue
		}

		var gongcheng models.Gongcheng
		data_source.Db.Where("title = ?", row[0]).Where("classify = ?", row[3]).First(&gongcheng)
		if gongcheng.ID == 0 {
			med := models.Gongcheng{
				Title:    row[0],
				Jieduan:  row[1],
				Name:     row[2],
				Classify: row[3],
				Content:  row[4],
				Zbtime:   row[5],
				Gongqi:   row[6],
				Status:   1,
				Addtime:  time.Now().Unix(),
			}
			data_source.Db.Create(&med)
		} else {
			num = num + 1
		}

	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "重复条数" + utils.Int64string(num),
		"msg":     "ok",
	})
	return
}
